package be.fomp.jeve.model.data.standard.sovereignty;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;

import be.fomp.jeve.model.data.AbstractResultImpl;
import be.fomp.jeve.model.data.standard.Sovereignty;

public final class SovereigntyImpl extends AbstractResultImpl implements Sovereignty{
	static final long serialVersionUID = 1L;
	
	private Map<Integer, SolarSystem> solarSystems = new HashMap<Integer, SolarSystem>();

	@SuppressWarnings("unchecked")
	public SovereigntyImpl(Document xmlDocument) {
		super(xmlDocument);

		Element root = xmlDocument.getRootElement();

		List<Element> resultSet = root.getChild("result").getChild("rowset").getChildren();
		for (Element solarSystemelement : resultSet) {
			SolarSystem solarSystem = new SolarSystemImpl(solarSystemelement);
			
			Integer solarSystemId = solarSystem.getSolarSystemID();

			this.solarSystems.put(solarSystemId, solarSystem);
		}
	}

	public Collection<SolarSystem> getSolarSystems() {
		return this.solarSystems.values();
	}

	public SolarSystem getSolarSystemById(Integer solarSystemId) {
		return this.solarSystems.get(solarSystemId);
	}

	public SolarSystem getSolarSystemByName(String solarSystemName) {
		SolarSystem returnValue = null;
		
		for(SolarSystem s: getSolarSystems()){
			if(solarSystemName.equals(s.getSolarSystemName())){
				returnValue = s;
				break;
			}
		}
		
		return returnValue;
	}
	
	public void writeObject(ObjectOutputStream os) {
		try {
			os.defaultWriteObject();
			os.writeObject(this.solarSystems);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void readObject(ObjectInputStream is) {
		try {
			is.defaultReadObject();
			this.solarSystems = ((Map<Integer, SolarSystem>) is.readObject());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
